<?php
/**
 * 亚马逊表格订单转换
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/11/19
 * Time: 22:29
 * @link http://www.lmterp.cn
 */

namespace app\common\service\platform\transform;

use app\common\library\Tools;
use app\common\model\Orders;
use app\common\service\BaseService;
use app\common\service\orders\OrderService;
use app\common\service\platform\AmazonService;

class AmazonOrder extends BaseService
{
    /**
     * amazon 文件订单路径
     * @var string
     */
    protected $file = '';

    /**
     * 哪个账号
     * @var int
     */
    protected $accountId;

    /**
     * 订单数据
     * @var array
     */
    protected $data = [];

    public function __construct($accountId, $file)
    {
        set_time_limit(0);
        $this->accountId = $accountId;
        $this->file = $file;
    }

    /**
     * 读取订单文件
     * @return array
     * @date 2020/11/19
     * @author longli
     */
    public function read()
    {
        $excel = new \app\common\library\FileExcel($this->file);
        $orders = $excel->read(function($order)
        {
            if(!$this->excludeOrder($order)) return $order;
        });
        if(!$orders) return join(", ", $excel->getError());
        $account = $this->getAccountById($this->accountId);
        $site = $account->getData('site') ? explode(',', $account->getData('site'))[0] : '';
        $service = new AmazonService($account->account_id);
        $defWarehouse = \app\common\model\Warehouse::getDefault();
        $offsetDate = date('Z'); // 时区偏移量
        $coverField = ['buyer_gender', 'buyer_company', 'consignee', 'buyer_first_name', 'buyer_email',
            'buyer_last_name', 'buyer_phone', 'buyer_mobile', 'buyer_province', 'buyer_district', 'buyer_email',
            'buyer_address_1', 'buyer_address_2', 'buyer_address_3', 'shipping_price',
            'payment_method', 'order_pay_time', 'invoice_type', 'invoice_title', 'invoice_detail',
            'shipping_method', 'platform_remark',
            ];
        foreach($orders as $order)
        {
            // 处理折扣
            $discount = 0;
            if(isset($order['item-promotion-discount']))
            {
                $discount = floatval($order['item-promotion-discount']);
            }
            else
            {
                $discount = isset($order['discount']) ? floatval($order['discount']) : 0;
                if($discount != 0 && Tools::contains($order['discount'], '%'))
                    $discount *= $order['item-price'] / 100;
            }

            // 检查订单是否有导入过
            $dorder = Orders::get(['order_no' => $order['amazon-order-id']]);
            $info = [[
                "item_id"       => null, // 商品 id
                "product_code"  => $order['asin'], // 商品编码
                "qty"           => $order['quantity'], // 数量
                "price"         => $order['item-price'] / $order['quantity'], // 售价
                "platform_sku"  => $order['sku'], // sku
                "name"          => $order['product-name'], // 产品名称
                "image_url"     => null, // 图片地址
                "discount"      => $discount, // 优惠金额
                "declare_en"    => !empty($order['declare_en']) ? $order['declare_en'] : '',  // 申报英文名
                "declare_ch"    => !empty($order['declare_ch']) ? $order['declare_ch'] : '', // 申报中文名
                "declare_price" => !empty($order['declare_price']) ? $order['declare_price'] : '', // 申报价格
                "url"           => $service->fillUrl($order['asin'], $site), // 商品链接
            ]];
            $price = floatval($order['item-price']);
            $tempOrder = [];
            if(isset($this->data[$order['amazon-order-id']]))
            {
                $tempOrder = $this->data[$order['amazon-order-id']];
                $info = array_merge($this->data[$order['amazon-order-id']]['order_detail'], $info);
                $price += $this->data[$order['amazon-order-id']]['order_price'];
            }
            $this->data[$order['amazon-order-id']] = [
                'order_id'                  => !empty($dorder) ? $dorder->order_id : null,
                "order_no"                  => $order['amazon-order-id'],
                "account_id"                => $account->account_id,
                "platform_name"             => $account->platform->name, // 平台名称
                "order_platform_status"     => $order['order-status'], // 订单在平台的状态
                "buyer_gender"              => !empty($order['buyer_gender']) ? $order['buyer_gender'] : '', // 客户性别
                "buyer_company"             => !empty($order['buyer_company']) ? $order['buyer_company'] : '', // 客户公司
                'consignee'                 => !empty($order['consignee']) ? $order['consignee'] : '', // 收件人
                "buyer_first_name"          => !empty($order['buyer_first_name']) ? $order['buyer_first_name'] : '', // 客户名称
                "buyer_last_name"           => !empty($order['buyer_last_name']) ? $order['buyer_last_name'] : '', // 客户名称
                "buyer_phone"               => !empty($order['buyer_phone']) ? $order['buyer_phone'] : '', // 电话
                "buyer_mobile"              => !empty($order['buyer_mobile']) ? $order['buyer_mobile'] : '', // 手机
                "buyer_email"               => !empty($order['buyer_email']) ? $order['buyer_email'] : '', // 买家邮箱
                "buyer_country"             => '', // 国家
                "buyer_country_code"        => $order['ship-country'], // 国家编码
                'buyer_province'            => !empty($order['ship-state']) ? $order['ship-state'] : $order['ship-city'], // 买家所在省，州
                "buyer_district"            => !empty($order['District']) ? $order['District'] : '', // 区
                "buyer_city"                => $order['ship-city'], // 城市
                "buyer_post_code"           => $order['ship-postal-code'], // 邮编
                "buyer_address_1"           => !empty($order['buyer_address_1']) ? $order['buyer_address_1'] : '', // 买家收货地址1
                "buyer_address_2"           => !empty($order['buyer_address_2']) ? $order['buyer_address_2'] : '', // 买家收货地址2
                "buyer_address_3"           => !empty($order['buyer_address_3']) ? $order['buyer_address_3'] : '', // 买家收货地址3
                "shipping_price"            => !empty($order['shipping_price']) ? $order['shipping_price'] : null, // 订单运费
                "order_source_create_time"  => $service->parseTimeToDate($order['purchase-date'], $offsetDate), // 订单在平台生成的时间
                "payment_method"            => !empty($order['payment_method']) ? $order['payment_method'] : '', // 支付方式
                "coupon_price"              => !empty($order['coupon_price']) ? floatval($order['coupon_price']) : 0, // 优惠券金额
                "order_price"               => $price, // 订单金额
                "total_price"               => $price, // 订单总金额
                "order_pay_time"            => !empty($order['order_pay_time']) ? $order['order_pay_time'] : null, // 订单支付时间
                "currency"                  => $order['currency'], // 币种
                "invoice_type"              => !empty($order['invoice_type']) ? $order['invoice_type'] : null, // 发票种类
                "invoice_title"             => !empty($order['invoice_title']) ? $order['invoice_title'] : null, // 发票抬头
                "invoice_detail"            => !empty($order['invoice_detail']) ? $order['invoice_detail'] : null, // 发票详情
                "track_num"                 => $order['fulfillment-channel'] == 'Amazon' ? 'FBA' : (!empty($order['track_num']) ? $order['track_num'] : ''), // 追踪号
                "shipping_method"           => !empty($order['shipping_method']) ? $order['shipping_method'] : null, // 运输方式
                "platform_remark"           => !empty($order['platform_remark']) ? $order['platform_remark'] : '', // 买家备注信息
                "order_detail"              => $info,
            ];
            if($order['fulfillment-channel'] == 'Amazon')
            {
                // 亚马逊订单
                $isCancel = $order['order-status'] == 'Cancelled';
                $this->data[$order['amazon-order-id']] += [
                    'is_flag_sent' => Orders::FLAG_SENT_NO_NEED, // 不需要标记
                    'order_status' => $isCancel ? Orders::ORDER_CANCEL : Orders::ORDER_SUCCESS, // 订单完成
                    'send_status'  => Orders::SEND_NO_NEED, // 无需发货
                    'warehouse_id' => $defWarehouse ? $defWarehouse->warehouse_id : 0, // FBA订单分配到默认仓库
                ];
            }
            else
            {
                // 自发货订单
                $sourceTime = $this->data[$order['amazon-order-id']]['order_source_create_time'];
                $this->data[$order['amazon-order-id']] += [
                    "latest_delivery_time" =>  date('Y-m-d', strtotime($sourceTime . "+{$account->send_day}day")), // 最迟发货时间
                ];
            }
            // 检查空字段
            if(!empty($tempOrder))
            {
                $pOrder = & $this->data[$order['amazon-order-id']];
                foreach($coverField as $f)
                {
                    if(empty($pOrder[$f])) $pOrder[$f] = $tempOrder[$f];
                }
            }
        }
        return $this->data;
    }

    /**
     * 保存订单数据
     * @return void
     * @date 2020/11/19
     * @author longli
     */
    public function push()
    {
        foreach($this->getData() as $order)
        {
            OrderService::getInstance()->addOrder($order);
        }
    }

    /**
     * 排除不需要的订单
     * @return bool
     * @date 2020/11/19
     * @author longli
     */
    public function excludeOrder($order = [])
    {
        if(empty($order['item-price'])) return true;
        // FBA 订单
        if($order['fulfillment-channel'] == 'Amazon')
        {
            if(empty($order['order-status'])) return true;
        }
        else
        {
            if(empty($order['order-status']) || trim($order['order-status']) == 'Cancelled') return true;
            if(empty($order['item-status']) || trim($order['item-status']) != 'Unshipped') return true;
        }
        return false;
    }

    /**
     * @return array
     */
    public function getData()
    {
        return $this->data;
    }
}